package com.TeaManage.servlet;

import com.TeaManage.bean.CustomerAddress;
import com.TeaManage.bean.Customer;
import com.TeaManage.util.GokJDBCUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

@WebServlet(name = "AddressServlet", urlPatterns = "/AddressServlet")
public class AddressServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        String action = request.getParameter("action");
        
        if ("add".equals(action)) {
            // 添加地址
            String customerIdStr = request.getParameter("customer_id");
            String receiverName = request.getParameter("receiver_name");
            String receiverPhone = request.getParameter("receiver_phone");
            String province = request.getParameter("province");
            String city = request.getParameter("city");
            String district = request.getParameter("district");
            String detailedAddress = request.getParameter("detailed_address");
            String isDefaultStr = request.getParameter("is_default");
            
            // 验证必填字段
            if (customerIdStr == null || customerIdStr.trim().isEmpty() ||
                receiverName == null || receiverName.trim().isEmpty() ||
                receiverPhone == null || receiverPhone.trim().isEmpty() ||
                province == null || province.trim().isEmpty() ||
                city == null || city.trim().isEmpty() ||
                district == null || district.trim().isEmpty() ||
                detailedAddress == null || detailedAddress.trim().isEmpty()) {
                request.setAttribute("error", "所有字段都必须填写");
                loadCustomersForAdd(request);
                request.getRequestDispatcher("/views/address/addAddress.jsp").forward(request, response);
                return;
            }
            
            // 验证电话格式
            if (!isValidPhone(receiverPhone)) {
                request.setAttribute("error", "收货人电话格式不正确");
                loadCustomersForAdd(request);
                request.getRequestDispatcher("/views/address/addAddress.jsp").forward(request, response);
                return;
            }
            
            try {
                int customerId = Integer.parseInt(customerIdStr);
                int isDefault = isDefaultStr != null ? Integer.parseInt(isDefaultStr) : 0;
                
                // 如果设置为默认地址，先将该客户的其他地址设为非默认
                if (isDefault == 1) {
                    String updateDefaultSql = "UPDATE customer_address SET is_default = 0 WHERE customer_id = ?";
                    GokJDBCUtil.update(updateDefaultSql, customerId);
                }
                
                String sql = "INSERT INTO customer_address(customer_id, receiver_name, receiver_phone, province, city, district, detailed_address, is_default) VALUES(?, ?, ?, ?, ?, ?, ?, ?)";
                int result = GokJDBCUtil.update(sql, customerId, receiverName, receiverPhone, province, city, district, detailedAddress, isDefault);
                
                if (result > 0) {
                    response.sendRedirect("AddressServlet");
                }
                
            } catch (NumberFormatException e) {
                request.setAttribute("error", "客户ID格式不正确");
                loadCustomersForAdd(request);
                request.getRequestDispatcher("/views/address/addAddress.jsp").forward(request, response);
            }
            
        } else if ("toAdd".equals(action)) {
            // 跳转到新增页面
            loadCustomersForAdd(request);
            request.getRequestDispatcher("/views/address/addAddress.jsp").forward(request, response);
            
        } else if ("deleteById".equals(action)) {
            // 删除地址
            int id = Integer.parseInt(request.getParameter("id"));
            String sql = "DELETE FROM customer_address WHERE address_id = ?";
            int result = GokJDBCUtil.update(sql, id);
            response.sendRedirect("AddressServlet");
            
        } else if ("findById".equals(action)) {
            // 查找地址用于编辑
            int id = Integer.parseInt(request.getParameter("id"));
            String sql = "SELECT ca.address_id, ca.customer_id, ca.receiver_name, ca.receiver_phone, ca.province, ca.city, ca.district, ca.detailed_address, ca.is_default, c.customer_name FROM customer_address ca LEFT JOIN customer c ON ca.customer_id = c.customer_id WHERE ca.address_id = ?";
            CustomerAddress address = GokJDBCUtil.queryForObject(sql, CustomerAddress.class, id);
            request.setAttribute("address", address);
            request.getRequestDispatcher("/views/address/editAddress.jsp").forward(request, response);
            
        } else if ("update".equals(action)) {
            // 更新地址
            int id = Integer.parseInt(request.getParameter("address_id"));
            String receiverName = request.getParameter("receiver_name");
            String receiverPhone = request.getParameter("receiver_phone");
            String province = request.getParameter("province");
            String city = request.getParameter("city");
            String district = request.getParameter("district");
            String detailedAddress = request.getParameter("detailed_address");
            String isDefaultStr = request.getParameter("is_default");
            
            // 验证必填字段
            if (receiverName == null || receiverName.trim().isEmpty() ||
                receiverPhone == null || receiverPhone.trim().isEmpty() ||
                province == null || province.trim().isEmpty() ||
                city == null || city.trim().isEmpty() ||
                district == null || district.trim().isEmpty() ||
                detailedAddress == null || detailedAddress.trim().isEmpty()) {
                request.setAttribute("error", "所有字段都必须填写");
                CustomerAddress address = GokJDBCUtil.queryForObject("SELECT ca.address_id, ca.customer_id, ca.receiver_name, ca.receiver_phone, ca.province, ca.city, ca.district, ca.detailed_address, ca.is_default, c.customer_name FROM customer_address ca LEFT JOIN customer c ON ca.customer_id = c.customer_id WHERE ca.address_id = ?", CustomerAddress.class, id);
                request.setAttribute("address", address);
                request.getRequestDispatcher("/views/address/editAddress.jsp").forward(request, response);
                return;
            }
            
            // 验证电话格式
            if (!isValidPhone(receiverPhone)) {
                request.setAttribute("error", "收货人电话格式不正确");
                CustomerAddress address = GokJDBCUtil.queryForObject("SELECT ca.address_id, ca.customer_id, ca.receiver_name, ca.receiver_phone, ca.province, ca.city, ca.district, ca.detailed_address, ca.is_default, c.customer_name FROM customer_address ca LEFT JOIN customer c ON ca.customer_id = c.customer_id WHERE ca.address_id = ?", CustomerAddress.class, id);
                request.setAttribute("address", address);
                request.getRequestDispatcher("/views/address/editAddress.jsp").forward(request, response);
                return;
            }
            
            try {
                int isDefault = isDefaultStr != null ? Integer.parseInt(isDefaultStr) : 0;
                
                // 获取当前地址的客户ID
                String getCustomerSql = "SELECT customer_id FROM customer_address WHERE address_id = ?";
                CustomerAddress currentAddress = GokJDBCUtil.queryForObject(getCustomerSql, CustomerAddress.class, id);
                
                // 如果设置为默认地址，先将该客户的其他地址设为非默认
                if (isDefault == 1 && currentAddress != null) {
                    String updateDefaultSql = "UPDATE customer_address SET is_default = 0 WHERE customer_id = ? AND address_id != ?";
                    GokJDBCUtil.update(updateDefaultSql, currentAddress.getCustomer_id(), id);
                }
                
                String sql = "UPDATE customer_address SET receiver_name = ?, receiver_phone = ?, province = ?, city = ?, district = ?, detailed_address = ?, is_default = ? WHERE address_id = ?";
                int result = GokJDBCUtil.update(sql, receiverName, receiverPhone, province, city, district, detailedAddress, isDefault, id);
                
                if (result > 0) {
                    response.sendRedirect("AddressServlet");
                }
                
            } catch (NumberFormatException e) {
                request.setAttribute("error", "数据格式不正确");
                CustomerAddress address = GokJDBCUtil.queryForObject("SELECT ca.address_id, ca.customer_id, ca.receiver_name, ca.receiver_phone, ca.province, ca.city, ca.district, ca.detailed_address, ca.is_default, c.customer_name FROM customer_address ca LEFT JOIN customer c ON ca.customer_id = c.customer_id WHERE ca.address_id = ?", CustomerAddress.class, id);
                request.setAttribute("address", address);
                request.getRequestDispatcher("/views/address/editAddress.jsp").forward(request, response);
            }
            
        } else if ("setDefault".equals(action)) {
            // 设置默认地址
            int id = Integer.parseInt(request.getParameter("id"));
            
            // 获取地址的客户ID
            String getCustomerSql = "SELECT customer_id FROM customer_address WHERE address_id = ?";
            CustomerAddress address = GokJDBCUtil.queryForObject(getCustomerSql, CustomerAddress.class, id);
            
            if (address != null) {
                // 先将该客户的所有地址设为非默认
                String updateAllSql = "UPDATE customer_address SET is_default = 0 WHERE customer_id = ?";
                GokJDBCUtil.update(updateAllSql, address.getCustomer_id());
                
                // 再将当前地址设为默认
                String updateCurrentSql = "UPDATE customer_address SET is_default = 1 WHERE address_id = ?";
                GokJDBCUtil.update(updateCurrentSql, id);
            }
            
            response.sendRedirect("AddressServlet");
            
        } else if ("search".equals(action)) {
            // 搜索地址
            String customerName = request.getParameter("customerName");
            String receiverName = request.getParameter("receiverName");
            String province = request.getParameter("province");
            String city = request.getParameter("city");
            
            // 分页参数
            int page = 1;
            int pageSize = 10;
            try {
                page = Integer.parseInt(request.getParameter("page"));
                pageSize = Integer.parseInt(request.getParameter("pageSize"));
            } catch (Exception e) {
                page = 1;
                pageSize = 10;
            }
            
            // 构建动态 SQL 和参数列表
            StringBuilder sql = new StringBuilder("SELECT ca.address_id, ca.customer_id, ca.receiver_name, ca.receiver_phone, ca.province, ca.city, ca.district, ca.detailed_address, ca.is_default, c.customer_name FROM customer_address ca LEFT JOIN customer c ON ca.customer_id = c.customer_id WHERE 1=1");
            List<Object> params = new ArrayList<>();
            
            if (customerName != null && !customerName.trim().isEmpty()) {
                sql.append(" AND c.customer_name LIKE ?");
                params.add("%" + customerName + "%");
            }
            if (receiverName != null && !receiverName.trim().isEmpty()) {
                sql.append(" AND ca.receiver_name LIKE ?");
                params.add("%" + receiverName + "%");
            }
            if (province != null && !province.trim().isEmpty()) {
                sql.append(" AND ca.province LIKE ?");
                params.add("%" + province + "%");
            }
            if (city != null && !city.trim().isEmpty()) {
                sql.append(" AND ca.city LIKE ?");
                params.add("%" + city + "%");
            }
            
            // 查询总数
            String countSql = "SELECT COUNT(*) FROM (" + sql.toString() + ") AS total";
            int total = GokJDBCUtil.queryForCount(countSql, params.toArray());
            
            // 添加分页
            sql.append(" ORDER BY ca.address_id DESC LIMIT ?, ?");
            params.add((page - 1) * pageSize);
            params.add(pageSize);
            
            List<CustomerAddress> addressList = GokJDBCUtil.queryAll(sql.toString(), CustomerAddress.class, params.toArray());
            
            // 计算总页数
            int totalPages = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
            
            // 返回结果
            request.setAttribute("addressList", addressList);
            request.setAttribute("customerName", customerName);
            request.setAttribute("receiverName", receiverName);
            request.setAttribute("province", province);
            request.setAttribute("city", city);
            request.setAttribute("page", page);
            request.setAttribute("pageSize", pageSize);
            request.setAttribute("totalPages", totalPages);
            request.getRequestDispatcher("views/address/address.jsp").forward(request, response);
            
        } else {
            // 默认显示地址列表
            loadAddressList(request, response);
        }
    }
    
    private void loadAddressList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 分页参数
        int page = 1;
        int pageSize = 10;
        try {
            page = Integer.parseInt(request.getParameter("page"));
            pageSize = Integer.parseInt(request.getParameter("pageSize"));
        } catch (Exception e) {
            page = 1;
            pageSize = 10;
        }
        
        // 查询总数
        String countSql = "SELECT COUNT(*) FROM customer_address";
        int total = GokJDBCUtil.queryForCount(countSql);
        
        // 查询数据
        String sql = "SELECT ca.address_id, ca.customer_id, ca.receiver_name, ca.receiver_phone, ca.province, ca.city, ca.district, ca.detailed_address, ca.is_default, c.customer_name FROM customer_address ca LEFT JOIN customer c ON ca.customer_id = c.customer_id ORDER BY ca.address_id DESC LIMIT ?, ?";
        List<CustomerAddress> addressList = GokJDBCUtil.queryAll(sql, CustomerAddress.class, (page-1)*pageSize, pageSize);
        
        int totalPages = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
        
        request.setAttribute("addressList", addressList);
        request.setAttribute("page", page);
        request.setAttribute("pageSize", pageSize);
        request.setAttribute("totalPages", totalPages);
        request.getRequestDispatcher("views/address/address.jsp").forward(request, response);
    }
    
    private void loadCustomersForAdd(HttpServletRequest request) {
        // 获取所有有效客户
        String customerSql = "SELECT * FROM customer WHERE status = 1 ORDER BY customer_name";
        List<Customer> customerList = GokJDBCUtil.queryAll(customerSql, Customer.class);
        request.setAttribute("customerList", customerList);
    }
    
    private boolean isValidPhone(String phone) {
        // 简单的电话号码验证：11位数字或带区号的固定电话
        String phonePattern = "^(1[3-9]\\d{9}|0\\d{2,3}-?\\d{7,8})$";
        return Pattern.matches(phonePattern, phone);
    }
}
